﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WpfSnqkGasAnalysis.Model;
using WpfSnqkGasAnalysis.IData;
using WpfSnqkGasAnalysis.Common;


namespace WpfSnqkGasAnalysis.IBusiness_impl
{
    /// <summary>
    /// 有机硫，业务处理
    /// </summary>
    /// 创建时间：2022-12-27 10:12:49。作者：王浩力
    public class SulfurBusiness : BaseBusiness
    {
        readonly IOrganic_sulfurDAL organic_SulfurDAL = ServicesHelpter.GetService<IOrganic_sulfurDAL>();
        readonly IOrganic_sulfur_check_historyDAL historyDAL = ServicesHelpter.GetService<IOrganic_sulfur_check_historyDAL>();
        readonly ISource_dictDAL source_DictDAL = ServicesHelpter.GetService<ISource_dictDAL>();

        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="where"></param>
        /// <param name="p"></param>
        /// <param name="rows"></param>
        /// <returns></returns>
        public PageModel<Organic_sulfur> GetPage(Organic_sulfur where, int p, int rows)
        {
            if (CurrentLoginUser.Role_id == "校对人")
            {
                where.WorkList = new List<int>() { 1, 3 };
            }
            else if (CurrentLoginUser.Role_id == "审核人")
            {
                where.WorkList = new List<int>() { 2 };
            }
            return organic_SulfurDAL.Page(where, p, rows);
        }

        /// <summary>
        /// 根据主键查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Organic_sulfur Get(long id)
        {
            return organic_SulfurDAL.Get(id);
        }

        public IResult Edit(Organic_sulfur organic_Sulfur)
        {
            if (organic_Sulfur == null)
            {
                return new Result("无效参数");
            }
            var old = organic_SulfurDAL.Get(organic_Sulfur.Id);
            if (!old.Samp_no.Equals(organic_Sulfur.Samp_no))
            {
                //检查样品编号是否存在
                var page = organic_SulfurDAL.Page(new Organic_sulfur() { Samp_no = organic_Sulfur.Samp_no }, 1, 1);
                if (page.Total > 0)
                {
                    return new Result("样品编号已存在，请重新输入");
                }
            }

            return organic_SulfurDAL.Edit(organic_Sulfur);
        }
        public IResult Add(Organic_sulfur organic_Sulfur)
        {
            organic_Sulfur.CreateUserId = CurrentLoginUser.Id;
            organic_Sulfur.CreateUser = CurrentLoginUser.User_real_name;
            organic_Sulfur.StepS = 1;

            //检查样品编号是否存在
            var page = organic_SulfurDAL.Page(new Organic_sulfur() { Samp_no = organic_Sulfur.Samp_no }, 1, 1);
            if (page.Total > 0)
            {
                return new Result("样品编号已存在，请重新输入");
            }

            return organic_SulfurDAL.Add(organic_Sulfur);
        }

        /// <summary>
        /// 标记删除
        /// </summary>
        /// <param name="organic_SulfurKEY"></param>
        /// <returns></returns>
        public IResult Delete(long organic_SulfurKEY)
        {
            var old = organic_SulfurDAL.Get(organic_SulfurKEY);
            if (old == null)
            {
                return new Result("没找到数据");
            }
            if (old.StepS == 4)
            {
                return new Result("审核通过的数据不可删除");
            }
            return organic_SulfurDAL.Delete(organic_SulfurKEY);
        }

        /// <summary>
        /// 校对
        /// </summary>
        /// <param name="organic_SulfurKEY"></param>
        /// <returns></returns>
        public IResult Proofread(Organic_sulfur info)
        {
            var old = organic_SulfurDAL.Get(info.Id);
            if (!old.Samp_no.Equals(info.Samp_no))
            {
                //检查样品编号是否存在
                var page = organic_SulfurDAL.Page(new Organic_sulfur() { Samp_no = info.Samp_no }, 1, 1);
                if (page.Total > 0)
                {
                    return new Result("样品编号已存在，请重新输入");
                }
            }
            info.StepS = 2;
            info.ProofreaderUserId = CurrentLoginUser.Id; //校对人id。添加时间：2023-1-9 17:01:25
            info.Proofreader = CurrentLoginUser.User_real_name;
            info.ProofreaderTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

            return organic_SulfurDAL.Proofreader(info);
        }

        /// <summary>
        /// 审核
        /// </summary>
        /// <param name="check_History"></param>
        /// <returns></returns>
        /// 创建时间：2022-12-27 10:17:00。作者：王浩力
        public IResult Check(Organic_sulfur_check_history check_History)
        {
            check_History.Check_user_id = CurrentLoginUser.Id;
            check_History.Check_user_name = CurrentLoginUser.User_real_name;
            check_History.Check_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            if (check_History.Check_stat == 0 && string.IsNullOrWhiteSpace(check_History.Reject_reason))
            {
                return new Result("驳回理由不可为空");
            }
            if (check_History.Organic_sulfurtId_ID == 0)
            {
                return new Result("无效参数");
            }
            return organic_SulfurDAL.Check(check_History);
        }

        /// <summary>
        /// 获取处理日志
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// 创建时间：2022-12-27 18:46:02。作者：王浩力
        public List<Organic_sulfur_check_history> GetHistory(long id)
        {
            var old = organic_SulfurDAL.Get(id);
            List<Organic_sulfur_check_history> list = new List<Organic_sulfur_check_history>();

            //审核历史
            var listHistory = historyDAL.GetList(id);

            Organic_sulfur_check_history one = new Organic_sulfur_check_history();
            one.Check_user_name = old.CreateUser;
            one.Check_time = old.Createtime;
            one.Reject_reason = "录入";
            list.Add(one);


            if (!string.IsNullOrWhiteSpace(old.Proofreader))
            {
                Organic_sulfur_check_history one2 = new Organic_sulfur_check_history();
                one2.Check_user_name = old.Proofreader;
                one2.Check_time = old.ProofreaderTime;
                one2.Reject_reason = "校对";
                list.Add(one2);
            }

            //审核
            if (listHistory?.Count > 0)
            {
                listHistory.ForEach(item =>
                {
                    if (item.Check_stat == 1)
                    {
                        item.Reject_reason = "审核通过";
                    }
                });
                list.AddRange(listHistory);
            }

            return list.OrderBy(g => g.Check_time).ToList();
        }

        /// <summary>
        /// 打印预览，读取各个项的文本值（下拉框）
        /// </summary>
        /// <param name="id"></param>
        /// 实现时间：2022-12-28 09:50:32。作者：王浩力
        public OrganicSulfurView GetView(long id)
        {
            var dictAll = source_DictDAL.GetAll();
            UserBusiness userBusiness = new UserBusiness();
            var allUser = userBusiness.GetAllUser();

            var info = organic_SulfurDAL.Get(id);
            var mapper = EmitMapper.ObjectMapperManager.DefaultInstance.GetMapper<Organic_sulfur, OrganicSulfurView>();
            OrganicSulfurView view = mapper.Map(info);

            view.Sampling_conditionsTXT = dictAll.FirstOrDefault(g => g.Id == view.Sampling_conditions.ToMyInt64())?.Item_name;
            view.ClientTXT = dictAll.FirstOrDefault(g => g.Id == view.Client.ToMyInt64())?.Item_name;

            //取样人，姓名
            view.Sampling_user_nameTXT = allUser.Find(g => g.Id == view.Sampling_user_name.ToMyInt64())?.User_real_name;

            view.Sampling_unitTXT = dictAll.FirstOrDefault(g => g.Id == view.Sampling_unit.ToMyInt64())?.Item_name;
            view.HorizonTXT = dictAll.FirstOrDefault(g => g.Id == view.Horizon.ToMyInt64())?.Item_name;
            view.Analysis_unitTXT = dictAll.FirstOrDefault(g => g.Id == view.Analysis_unit.ToMyInt64())?.Item_name;

            //取样位置，修改时间：2023-1-15 21:35:28。
            if (System.Text.RegularExpressions.Regex.IsMatch(view.Sampling_location, "^\\d*$"))
            {
                view.Sampling_locationTXT = dictAll.FirstOrDefault(g => g.Id == view.Sampling_location.ToMyInt64())?.Item_name;
            }
            else
            {
                view.Sampling_locationTXT = view.Sampling_location;
            }

            //创建时间：2023-1-13 14:10:36
            var fenxiren = allUser.FirstOrDefault(g => g.Id == view.Analysis_userID);

            //分析人姓名
            view.AnalystStr = fenxiren?.User_real_name;

            //分析人，电子签名
            view.E6 = fenxiren?.SignatureImgPath;

            //校对人，电子签名
            if (info.ProofreaderUserId != null && info.ProofreaderUserId > 0)
            {
                view.E7 = allUser.FirstOrDefault(g => g.Id == info.ProofreaderUserId)?.SignatureImgPath;
            }

            //审核人，电子签名
            //审核历史
            var history = historyDAL.GetList(id);
            if (history?.Count > 0)
            {
                var find = history.OrderByDescending(g => g.Id).FirstOrDefault();
                if (find != null)
                {
                    var ckUser = allUser.FirstOrDefault(g => g.Id == find.Check_user_id);
                    view.E5 = find?.Check_user_name;//审核人姓名
                    view.E8 = ckUser?.SignatureImgPath; //审核人电子签名图片url
                }
            }

            return view;
        }

    }
}
